package leetcode.day_2020_11_23_11_29;

import java.util.Stack;

public class L_32 {
    public static void main(String[] args) {
        String s = "()(()";
        System.out.println(longestValidParentheses(s));
    }

    public static int longestValidParentheses(String s) {
        Stack<Character> stack = new Stack();
        int length = s.length();
        if(length==0 || length==1)
            return 0;
        int i = 0;
        int count = 0;
        stack.push(s.charAt(i));
        while (i+1 < length) {
            i = i+1;
            if(stack.isEmpty()){
                stack.push(s.charAt(i));
            }else {
                if(stack.peek()=='('  && s.charAt(i)==')') {
                    count = count+2;
                    stack.pop();
                }else {
                    stack.push(s.charAt(i));
                }
            }
        }
        return count;
    }
}
